"""
Basic usage examples for imagetools library.
"""

from PIL import Image
import numpy as np
import sys
import os

# Add parent directory to path to import imagetools
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from imagetools import (
    load_image,
    detect_image_type,
    to_three_channel,
    to_single_channel,
    to_rgb,
    to_grayscale,
    is_grayscale,
    fix_channels,
    get_dimensions,
    print_image_info,
    ImageType,
)


def create_sample_images():
    """Create sample images for testing."""
    # Create a simple RGB image
    rgb_data = np.zeros((100, 100, 3), dtype=np.uint8)
    rgb_data[:, :, 0] = 255  # Red channel
    rgb_data[:, :, 1] = 128  # Green channel
    rgb_data[:, :, 2] = 64   # Blue channel
    rgb_img = Image.fromarray(rgb_data, 'RGB')

    # Create a grayscale image (single channel)
    gray_data = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
    gray_img = Image.fromarray(gray_data, 'L')

    # Create a grayscale image stored as RGB (all channels equal)
    gray_rgb_data = np.zeros((100, 100, 3), dtype=np.uint8)
    gray_val = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
    gray_rgb_data[:, :, 0] = gray_val
    gray_rgb_data[:, :, 1] = gray_val
    gray_rgb_data[:, :, 2] = gray_val
    gray_rgb_img = Image.fromarray(gray_rgb_data, 'RGB')

    return {
        'rgb': rgb_img,
        'grayscale_1c': gray_img,
        'grayscale_3c': gray_rgb_img,
    }


def main():
    print("=== ImageTools Basic Usage Examples ===\n")

    # Create sample images
    samples = create_sample_images()

    # Test each image
    for name, img in samples.items():
        print(f"\n--- Testing {name} image ---")
        print(f"Original mode: {img.mode}, size: {img.size}")

        # Detect image type
        info = detect_image_type(img)
        print(f"Detected type: {info['type']}")
        print(f"Channels: {info['channels']}")
        print(f"Is actual grayscale: {info['is_actual_grayscale']}")

        # Check if grayscale
        print(f"Is grayscale (threshold=1): {is_grayscale(img, threshold=1)}")

        # Convert to three channels
        three_channel = to_three_channel(img)
        print(f"3-channel mode: {three_channel.mode}")

        # Convert to single channel
        single_channel = to_single_channel(img, method='average')
        print(f"Single channel mode: {single_channel.mode}")

        # Fix channels to specific counts
        for target in [1, 3, 4]:
            fixed = fix_channels(img, target)
            print(f"Fixed to {target} channel(s): mode={fixed.mode}")

    # Test with RGBA image (simulated)
    print("\n--- Testing RGBA conversion ---")
    rgba_data = np.zeros((50, 50, 4), dtype=np.uint8)
    rgba_data[:, :, 0] = 255  # Red
    rgba_data[:, :, 3] = 128  # Alpha (semi-transparent)
    rgba_img = Image.fromarray(rgba_data, 'RGBA')
    print(f"RGBA image mode: {rgba_img.mode}")

    rgb_from_rgba = to_rgb(rgba_img)
    print(f"RGB from RGBA mode: {rgb_from_rgba.mode}")

    # Test grayscale conversion methods
    print("\n--- Testing grayscale conversion methods ---")
    rgb_img = samples['rgb']
    for method in ['average', 'luminosity', 'red', 'green', 'blue', 'max', 'min']:
        gray = to_grayscale(rgb_img, method=method)
        print(f"Method '{method}': mode={gray.mode}, size={gray.size}")

    # Test new dimension and info functions
    print("\n--- Testing dimension and info functions ---")
    for name, img in samples.items():
        print(f"\n{name}:")
        # Get dimensions
        width, height, channels = get_dimensions(img)
        print(f"  Dimensions: {width} x {height}, Channels: {channels}")

        # Print detailed info
        print(f"  Detailed info:")
        print_image_info(img, title=f"{name} Image")

    print("\n=== Examples completed ===")


if __name__ == '__main__':
    main()